#!/bin/bash
# 功能: 安装 MySQL
# 名称: mysql_install.sh
# 作者: zxm
# 创建日期: 2024-11-26
# 版本: v1.0

FIND_STR="UINO_HOME"
FIND_FILE_ETC_PROFILE=/etc/profile
FIND_FILE_BASHRC=~/.bashrc
FIND_FILE_BASH_PROFILE=~/.bash_profile

etc_profile_num=$(grep -c $FIND_STR $FIND_FILE_ETC_PROFILE)
bashrc_num=$(grep -c $FIND_STR $FIND_FILE_BASHRC)
bash_profile=$(grep -c $FIND_STR $FIND_FILE_BASH_PROFILE)

if [[ ! ${UINO_HOME} ]] && [[ ${etc_profile_num} -eq '0' ]] && [[ ${bashrc_num} -eq '0' ]] && [[ ${bash_profile} -eq '0' ]]; then
  echo "UINO_HOME is not exist,please input a directory to install(default:/uino)"
  read UINO_INPUT
  if [ ! ${UINO_INPUT} ]; then
    UINO_INPUT=/uino
  fi
  if [ ! -d ${UINO_INPUT} ]; then
    mkdir -p ${UINO_INPUT}
  fi
  if [ -w "${UINO_INPUT}" ] && [ -x "${UINO_INPUT}" ]; then
    echo "modify privileages ...."
  else
    echo "you have no permission with ${UINO_INPUT},please conntact administrator to add permission or use another directory!"
    exit 0
  fi
  echo "export UINO_HOME=${UINO_INPUT}" >>~/.bashrc
  source ~/.bashrc
elif [[ ! ${UINO_HOME} ]] && [[ ${etc_profile_num} -gt '0' ]] && [[ ${bashrc_num} -eq '0' ]] && [[ ${bash_profile} -eq '0' ]]; then
  source /etc/profile
elif [[ ! ${UINO_HOME} ]] && [[ ${etc_profile_num} -eq '0' ]] && [[ ${bashrc_num} -gt '0' ]] && [[ ${bash_profile} -eq '0' ]]; then
  source ~/.bashrc
elif [[ ! ${UINO_HOME} ]] && [[ ${etc_profile_num} -eq '0' ]] && [[ ${bashrc_num} -eq '0' ]] && [[ ${bash_profile} -eq '0' ]]; then
  source ~/.bash_profile
elif [[ ! ${UINO_HOME} ]] && [[ ${etc_profile_num} -gt '0' ]] && [[ ${bashrc_num} -gt '0' ]] && [[ ${bash_profile} -gt '0' ]]; then
  UINO_HOME exist in "/etc/profile" and "~/bashrc" and "~/bash_profile",please Re-install after clear two places
elif [[ ! ${UINO_HOME} ]] && [[ ${etc_profile_num} -gt '0' ]] && [[ ${bashrc_num} -gt '0' ]] && [[ ${bash_profile} -eq '0' ]]; then
  UINO_HOME exist in "/etc/profile" and "~/bashrc" ,please Re-install after clear one place
elif [[ ! ${UINO_HOME} ]] && [[ ${etc_profile_num} -gt '0' ]] && [[ ${bashrc_num} -eq '0' ]] && [[ ${bash_profile} -gt '0' ]]; then
  UINO_HOME exist in "/etc/profile" and "~/bash_profile",please Re-install after clear one place
elif [[ ! ${UINO_HOME} ]] && [[ ${etc_profile_num} -eq '0' ]] && [[ ${bashrc_num} -gt '0' ]] && [[ ${bash_profile} -gt '0' ]]; then
  UINO_HOME exist in "~/.bashrc" and "~/bash_profile",please Re-install after clear one place
else
  echo "UINO_HOME is ${UINO_HOME}"
fi
cd $(dirname $0)
MYSQL_DIR=${UINO_HOME}/mysql_tarsier_linux
USERNAME=$(whoami)
mkdir -p ${MYSQL_DIR}
if [[ ! -w ${MYSQL_DIR} ]]; then
  echo "user ${USERNAME} has no permission to write in this directory,please modify the value of the UINO_HOME in ~/.bashrc,and re_install again!"
  exit
fi

if [[ -d "${MYSQL_DIR}/data" ]]; then
  echo "mysql has data already,do you want to clear the data and initialize it again?(please input yes or no,default:no)"
  read clearData
  while [ ! ${clearData} ]; do
    read clearData
  done
  clearData_tmp=$(echo $clearData | tr [a-z] [A-Z])
  if [ ${clearData_tmp} != "YES" ]; then
    exit
  fi
fi
#检查是否安装libaio
#result=`dpkg -s libaio1`
if [ -x "$(command -v dpkg)" ]; then
  # Debian or Ubuntu
  result=$(dpkg -s libaio1)
elif [ -x "$(command -v rpm)" ]; then
  # CentOS
  result=$(rpm -q libaio)
else
  echo "Unsupported distribution"
  exit 1
fi

echo ${result}

if [[ ! ${result} =~ "libaio" ]]; then
  echo "libaio not exit,please install libaio first!"
  exit
else
  #删除已存在进程
  pid_list=$(ps -ef | grep "mysqld_safe" | grep -v grep | awk '{print $2}')
  for pid in ${pid_list}; do
    echo "PID:${pid}"
    pid_user=$(ps -ef | grep mysqld_safe | grep -v grep | awk '{print $1}')
    if [[ ${USERNAME} != "root" ]] && [[ ${USERNAME} != ${pid_user} ]]; then
      echo "mysql pid is alread exists,${USERNAME} has no permission kill it,please kill it use other user"
      exit
    fi
    kill -9 ${pid} >/dev/null 2>&1
  done

  pid_list=$(ps -ef | grep "mysqld" | grep -v grep | awk '{print $2}')
  for pid in ${pid_list}; do
    echo "PID:${pid}"
    kill -9 ${pid} >/dev/null 2>&1
  done
  #清除已有数据
  rm -rf ${MYSQL_DIR}
  echo "uncompress install file"
  tar zxf mysql_tarsier_linux.tar.gz -C ${UINO_HOME}
  #接收安装参数
  function receiveparam() {
    echo -e "please input\033[31m local node\033[0m port(default:1541)"
    read localport
    if [ ! ${localport} ]; then
      localport=1541
    fi

    echo -e "please input\033[31m local node\033[0m username(default:uinnova)"
    read -r localusername
    while ([ ! ${localusername} ] || [ ${localusername} == "root" ]); do
      if [ ! ${localusername} ]; then
        localusername="uinnova"
      fi

      if [ ${localusername} == "root" ]; then
        echo "root is a default user,please input another username:(default:uinnova)"
        read -r localusername
      fi
    done

    if [[ ${localusername} =~ "\\" ]]; then
      localusername=${localusername/\\/\\\\}
    fi

    if [[ ${localusername} =~ "'" ]]; then
      localusername=${localusername/\'/\\\'}
    fi

    echo -e "please input\033[31m local node\033[0m password(default:Uinnova@123)"
    read -r localpassword
    if [ ! ${localpassword} ]; then
      localpassword="Uinnova@123"
    fi
    if [[ ${localpassword} =~ "\\" ]]; then
      localpassword=${localpassword/\\/\\\\}
    fi
    if [[ ${localpassword} =~ "'" ]]; then
      localpassword=${localpassword/\'/\\\'}
    fi

    echo "please input language type:(zh or en,default:zh)"
    read lanType
    if [ ! ${lanType} ]; then
      lanType=zh
    fi
    lanType_tmp=$(echo ${lanType} | tr [a-z] [A-Z])
    if [ ${lanType_tmp} != "EN" ]; then
      lanType=zh
    fi
  }
  nodeRole=""

  echo "please input install type:(1:calssic;2:custom,please input 1 or 2,default:1)"
  read install_type
  if [ ! ${install_type} ]; then
    install_type=1
  fi
  if [ ${install_type} == 2 ]; then
    echo "please input install mode:(1:single;2:cluster,please input 1 or 2)"
    read installmode
    while [ ! ${installmode} ]; do
      read installmode
    done
    if [ ${installmode} == 1 ]; then
      nodeRole=1
      receiveparam
    else
      echo -e "please input\033[31m local node\033[0m identity(1:master,2:slave,please input 1 or 2)"
      read localiden
      while [ ! ${localiden} ]; do
        read localiden
      done
      receiveparam
      nodeRole=2
      if [ ${localiden} == 2 ]; then
        nodeRole=3
        echo -e "please input\033[31m master IP \033[0m"
        read masterip
        while [ ! ${masterip} ]; do
          read masterip
        done

        echo -e "please input\033[31m master port\033[0m (default:1541)"
        read masterport
        if [ ! ${masterport} ]; then
          masterport=1541
        fi

        echo -e "please input\033[31m master username\033[0m (default:uinnova)"
        read -r masteruser
        if [ ! ${masteruser} ]; then
          masteruser="uinnova"
        fi
        masteruser_value=${masteruser}
        if [[ ${masteruser_value} =~ "\\" ]]; then
          masteruser_value=${masteruser_value/\\/\\\\}
        fi
        if [[ ${masteruser_value} =~ "'" ]]; then
          masteruser_value=${masteruser_value/\'/\\\'}
        fi

        echo -e "please input \033[31m master password\033[0m (default:Uinnova@123)"
        read -r masterpassword
        if [ ! ${masterpassword} ]; then
          masterpassword="Uinnova@123"
        fi
        masterpassword_value=${masterpassword}
        if [[ ${masterpassword_value} =~ "\\" ]]; then
          masterpassword_value=${masterpassword_value/\\/\\\\}
        fi
        if [[ ${masterpassword_value} =~ "'" ]]; then
          masterpassword_value=${masterpassword_value/\'/\\\'}
        fi

      fi
    fi
  else
    localusername="uinnova"
    localpassword="Uinnova@123"
    localport=1541
    lanType=zh
    nodeRole=1
  fi
  #修改配置文件
  echo "modify mysql configure file"
  sed -i 's#datadir=.*#datadir='${MYSQL_DIR}/data'#g' ${MYSQL_DIR}/my.cnf
  sed -i 's#basedir=.*#basedir='${MYSQL_DIR}'#g' ${MYSQL_DIR}/my.cnf
  sed -i 's#log_error=.*#log_error='${MYSQL_DIR}/data/error.log'#g' ${MYSQL_DIR}/my.cnf
  sed -i 's#socket=.*#socket='${MYSQL_DIR}/mysql.sock'#g' ${MYSQL_DIR}/my.cnf
  sed -i 's#port=.*#port='${localport}'#g' ${MYSQL_DIR}/my.cnf

  if [ ${nodeRole} == 1 ]; then
    sed -i '/mysqld/a\skip-log-bin' ${MYSQL_DIR}/my.cnf
  elif [ ${nodeRole} == 2 ] || [ ${nodeRole} == 3 ]; then
    sed -i '/mysqld/a\relay-log=relay-bin' ${MYSQL_DIR}/my.cnf
    serverid=$(date +%s)
    sed -i '/mysqld/a\log-bin=mysql-bin' ${MYSQL_DIR}/my.cnf
    sed -i '/mysqld/a\binlog_expire_logs_seconds=604800' ${MYSQL_DIR}/my.cnf
    sed -i '/mysqld/a\log_bin_trust_function_creators = 1' ${MYSQL_DIR}/my.cnf
    sed -i "/mysqld/a server-id=\\$serverid" ${MYSQL_DIR}/my.cnf
  else
    echo "some error happened!"
    exit
  fi

  #初使化mysql
  ${MYSQL_DIR}/bin/mysqld --defaults-file=${MYSQL_DIR}/my.cnf --initialize --basedir=${MYSQL_DIR} --datadir=${MYSQL_DIR}/data
  echo "modify mysql default password"
  #修改mysql密码
  ${MYSQL_DIR}/bin/mysqld_safe --defaults-file=${MYSQL_DIR}/my.cnf --user=${USERNAME} >/dev/null 2>&1 &
  num=0
  while [ ${num} -le 10 ]; do
    grep 33060 ${MYSQL_DIR}/data/error.log >/dev/null
    flag=$?
    if [ ${flag} != 0 ]; then
      sleep 3
    else
      break
    fi
    let num++
  done

  MYSQL_PASS=$(cat ${MYSQL_DIR}/data/error.log | grep root@localhost | awk '{print $13}')
  ${MYSQL_DIR}/bin/mysql -uroot -p${MYSQL_PASS} --connect-expired-password -S ${MYSQL_DIR}/mysql.sock -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Uinnova@123'" >/dev/null 2>&1

  #添加环境变量
  echo "MYSQL_HOME=${MYSQL_DIR}" >>~/.bashrc
  echo 'PATH=${MYSQL_HOME}/bin:$PATH' >>~/.bashrc
  echo "export MYSQL_HOME PATH" >>~/.bashrc
  source ~/.bashrc

  echo "add mysql user"

  ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use mysql;create user '${localusername}'@'%' identified by '${localpassword}';grant all on *.* to '${localusername}'@'%';" >/dev/null 2>&1
  ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "alter user '${localusername}'@'%' identified with mysql_native_password by'${localpassword}'" >/dev/null 2>&1
  ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use mysql;create user '${localusername}'@'127.0.0.1' identified by '${localpassword}';grant all on *.* to '${localusername}'@'127.0.0.1';" >/dev/null 2>&1

  #初使化数据
  # echo "CREATE SCHEMA `dix` DEFAULT CHARACTER SET utf8"

  # ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "create database db_vmdb default charset=utf8;use db_vmdb;source ${MYSQL_DIR}/initdata/${lanType}/01_tarsier_tables.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use db_vmdb;source ${MYSQL_DIR}/initdata/${lanType}/02_tarsier_init_data.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql  -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use db_vmdb;source ${MYSQL_DIR}/initdata/${lanType}/03_tarsier_emv_tables.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql  -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use db_vmdb;source ${MYSQL_DIR}/initdata/${lanType}/04_tarsier_dcv_tables.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use db_vmdb;source ${MYSQL_DIR}/initdata/${lanType}/05_tarsier_dcv_init_data.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use db_vmdb;source ${MYSQL_DIR}/initdata/${lanType}/07_event2.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use db_vmdb;source ${MYSQL_DIR}/initdata/${lanType}/08_smv.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use db_vmdb;source ${MYSQL_DIR}/initdata/${lanType}/09_pmv.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "source ${MYSQL_DIR}/initdata/${lanType}/10_DB.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "use dix;source ${MYSQL_DIR}/initdata/${lanType}/11_initDip.sql;" >/dev/null 2>&1
  # ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "create database dix default charset=utf8" >/dev/null 2>&1

  msyqld_safe=$(ps -ef | grep "mysqld_safe" | grep -v grep | awk '{print $2}')
  if [ {mysqld_safe} ]; then
    echo "mysql start successfully,mysql pid is:"
    ps -ef | grep "mysqld" | grep -v grep
    if [ ${install_type} == 1 ]; then
      echo "default username is: uinnova"
      echo "default password is: Uinnova@123"
      echo "default port is: 1541"
    fi
  fi

  #配置主备同步
  if [ ${nodeRole} == 3 ]; then
    echo "configure mysql synchronization"
    master_status=$(${MYSQL_DIR}/bin/mysql -h${masterip} -P${masterport} -u${masteruser} -p${masterpassword} -e "show master status;")
    len=$(echo ${master_status} | wc -L)
    if [ ${len} == 0 ]; then
      echo "Error:can not get the master's status!,please check master's configuration"
      exit
    fi
    master_file=$(echo "$master_status" | grep "bin" | awk '{print $1}')
    master_pos=$(echo "$master_status" | grep "bin" | awk '{print $2}')
    ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "change  master to master_host='${masterip}', master_port=${masterport},master_password='${masterpassword_value}', master_user='${masteruser_value}', master_log_file='${master_file}', master_log_pos=${master_pos};" >/dev/null 2>&1
    ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "flush privileges;" >/dev/null 2>&1
    ${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "start slave;" >/dev/null 2>&1
    sleep 2
    slave_status=$(${MYSQL_DIR}/bin/mysql -uroot -pUinnova@123 -S ${MYSQL_DIR}/mysql.sock -e "show slave status \G;" | grep -i "running")
    slaveiorunning=$(echo $slave_status | grep IO | awk ' {print $2}')
    slavesqlrunning=$(echo $slave_status | grep SQL | awk '{print $2}')
    echo "mysql synchronization configure finished"
    echo "Slave_IO_Running : ${slaveiorunning}"
    echo "Slave_SQL_Running : ${slavesqlrunning}"

    if [[ ${slaveiorunning} == "Yes" ]] && [[ ${slavesqlrunning} == "Yes" ]]; then
      echo "master and slave synchronize successfully"
    else
      echo "master and slave synchronize failed"
    fi
  fi
fi
pkill -9 initmysql.sh
